package com.saicmotor.pay.error;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.saicmotor.pay.util.StringUtil;

import org.jetbrains.annotations.NotNull;

import static com.saicmotor.pay.error.ErrorCodes.ERROR_CODE_UNKNOWN;


public class ErrorInfo {
    private String message;
    private String errorCode;
    private String errorPosition;

    public ErrorInfo(String errorPosition, Throwable throwable) {
        this.errorPosition = errorPosition;
        this.errorCode = ERROR_CODE_UNKNOWN;
        this.message = throwable.getMessage();

        String message = throwable.getMessage();
        if (null != message && StringUtil.isJsonStr(message)) {
            JsonElement jsonElement = JsonParser.parseString(message);
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                if (jsonObject.has("errorCode")) {
                    this.errorCode = jsonObject.get("errorCode").getAsString();
                }
                if (jsonObject.has("errorMessage")) {
                    this.message = jsonObject.get("errorMessage").getAsString();
                }
            }
        } else {
            this.errorCode = "other error";
            this.message = message;
        }
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorPosition() {
        return errorPosition;
    }

    public void setErrorPosition(String errorPosition) {
        this.errorPosition = errorPosition;
    }

    @NotNull
    @Override
    public String toString() {
        return new Gson().toJson(this);

    }
}
